package com.liming.common.excel;

import cn.hutool.core.util.ObjectUtil;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.FastExcel;
import cn.idev.excel.write.metadata.WriteSheet;

import java.util.List;


/**
 * @author liming
 * @date 2025/5/17
 */
public abstract class AbstractExcelExportTool<S, C> {

    private ExcelWriter excelWriter;
    private WriteSheet writeSheet;
    private AbstractExcelExportTool<S, ?> chain;

    /**
     * sheet编号
     *
     * @return sheetNo
     */
    protected abstract int getSheetNo();

    /**
     * sheet名称
     *
     * @return sheetName
     */
    protected abstract String getSheetName();

    /**
     * 最终导出的数据类型
     *
     * @return 导出数据类型
     */
    protected abstract Class<C> getHeadClass();

    /**
     * 初始化 主导出链
     * 不存在子导出链
     *
     * @param excelWriter ExcelWriter
     */
    private void init(ExcelWriter excelWriter) {
        init(excelWriter, null);
    }

    /**
     * 初始化 主导出链
     *
     * @param excelWriter ExcelWriter
     * @param chain       子导出链
     */
    public void init(ExcelWriter excelWriter, AbstractExcelExportTool<S, ?> chain) {
        this.excelWriter = excelWriter;
        this.writeSheet = FastExcel.writerSheet(getSheetNo(), getSheetName()).head(getHeadClass()).build();
        this.chain = chain;
    }

    /**
     * 原始数据转换
     *
     * @param sourceData 原始数据
     * @return 转换后的数据
     */
    protected abstract List<C> convertData(List<S> sourceData);

    /**
     * 导出数据
     *
     * @param excelWriter ExcelWriter
     * @param sourceData  原始数据
     */
    public void writeData(ExcelWriter excelWriter, List<S> sourceData) {
        this.init(excelWriter);
        this.excelWriter.write(convertData(sourceData), this.writeSheet);
        if (ObjectUtil.isNotNull(chain)) {
            chain.writeData(excelWriter, sourceData);
        }
    }
}
